package com.dreamer.view.pyramid;

import com.dreamer.domain.pyramid.Pyramid;
import com.dreamer.domain.user.User;
import com.dreamer.service.pyramid.PyramidHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import ps.mx.otter.utils.WebUtil;
import ps.mx.otter.utils.message.Message;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;

@RestController
@RequestMapping("/pyramid")
public class PyramidController {

    @Autowired
    private PyramidHandler pyramidHandler;

    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    public Message edit(@ModelAttribute("parameter") Pyramid pyramid) {
        pyramid.setUpdateTime(new Date());
        Pyramid pyramid1 = pyramidHandler.saveOrupdate(pyramid);
        if(pyramid1 != null){
            return Message.createSuccessMessage();
        }else{
            return Message.createFailedMessage();
        }
    }

    @ModelAttribute("parameter")
    public Pyramid preprocess(@RequestParam("id") Optional<Integer> id) {
        Pyramid pyramid;
        if (id.isPresent()) {
            pyramid = pyramidHandler.findById(id.get());
        }else{
            pyramid = new Pyramid();
        }
        return pyramid;
    }

    @RequestMapping(value = "/remove.json", method = RequestMethod.DELETE)
    public Message remove(
            @ModelAttribute("parameter") Pyramid parameter,HttpServletRequest request,
            Model model) {
        try{
            User user=(User)WebUtil.getCurrentUser(request);
            if(user.isAdmin()){
                pyramidHandler.remove(parameter);
            }else if(user.isAgent()){
                return Message.createFailedMessage("本操作仅限于管理员权限");
            }
            return Message.createSuccessMessage();
        }catch(Exception exp){
            exp.printStackTrace();
            return Message.createFailedMessage(exp.getMessage());
        }
    }

}
